import express from "express";
import fs from "fs";
import path from "path";
import ts from "typescript";

const app = express();
// 配置编译器选项
const compilerOptions = {
  target: ts.ScriptTarget.ES2016,
  module: ts.ModuleKind.CommonJS,
};

// web目录
const webDirname = path.resolve(__dirname, "../web");

app.use((req, res, next) => {
  if (req.url.endsWith(".js")) {
    const jsCode = fs.readFileSync(path.resolve(webDirname, "." + req.url));
    res.setHeader("Content-Type", "text/javascript");
    res.send(jsCode.toString());
  } else if (req.url.endsWith(".ts")) {
    try {
      const tsCode = fs
        .readFileSync(path.resolve(webDirname, "." + req.url))
        .toString();
      // 编译 TypeScript 代码为 JavaScript 代码
      const { outputText } = ts.transpileModule(tsCode, { compilerOptions });
      res.setHeader("Content-Type", "text/javascript");
      res.send(outputText);
    } catch (error) {
      console.error("转换过程中出现错误:", error);
      res.setHeader("Content-Type", "text/plain");
      res.status(500);
    }
  } else next();
});

app.get("/", (req, res) => {
  const result = fs.readFileSync(path.resolve(webDirname, "index.html"));
  res.setHeader("Content-Type", "text/html");
  res.send(result.toString());
});

app.listen(2025, () => {
  console.log("serve is running at http://localhost:2025");
});
